import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import easyDAO.SqlDispatch;
import models.MyConfig;
import models.ReturnJson;
import models.SqlReturnModel;
import models.User;
import tools.ReadProperties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Objects;

/**
 * Created by yangxianming on 2018/1/16.
 * 设备数据上传测试
 */
@WebServlet(name = "getHomePage", urlPatterns = {"/getHomePage/*"}, loadOnStartup = 2)
public class GetHomePage extends HttpServlet {
    MyConfig myConfig = new MyConfig();
    public void init(ServletConfig config) throws ServletException {
        ReadProperties readProperties = new ReadProperties(config.getServletContext().getRealPath("/"));
        myConfig.setPropertiesConfig(readProperties);
        myConfig.setSplitMark();
        myConfig.setUser(new User());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //start
        long start = new Date().getTime();

        response.setHeader("Content-type", "text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ReturnJson rj = new ReturnJson();
        String returnInfo = "";

        //首字母大写
//        char[] cs = request.getPathInfo().substring(1).toCharArray();
//        cs[0] -= 32;

        Class<?> action;
        try {

            HttpSession sh = request.getSession();
            String username = "";

            //验证密码
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie: cookies){
                if (Objects.equals(cookie.getName(), "JSESSIONID")){
                    User user = (User)sh.getAttribute(cookie.getValue());
                    username = user.getUsername();
                }
            }
            //拿到用户和admin数据
            SqlDispatch sqlDispatch = new SqlDispatch(myConfig);
            String sql1 = "SELECT username,power FROM `user` WHERE username IN ('POWERLIST', '"+username+"')";
            SqlReturnModel srm = sqlDispatch.selectWord(sql1);
            rj.setResult(1, getUserHomePage(srm), null);

//            action = Class.forName("videoBusiness." + String.valueOf(cs));
//            Method method = action.getDeclaredMethod("doIt", HttpServletRequest.class, MyConfig.class);
//            returnInfo = (String)method.invoke(action.newInstance(), request, myConfig);
        }catch (Exception e){
            e.printStackTrace();
        }

        //end
        long end = new Date().getTime();
        System.out.println(request.getRequestURI() + "; run time: " + (end-start) + "ms");

        out.print(rj);
    }

    @Override
    public void destroy()
    {
        // 什么也不做
    }

    private String  getUserHomePage(SqlReturnModel srm){
        JSONArray adminHomePage = new JSONArray();
        JSONArray userHomePage = new JSONArray();
        ArrayList<ArrayList<String>> userInfo = srm.getSelectReturnData();
        for (int i = 0; i < userInfo.size(); i++){
            if (userInfo.get(i).get(0).equals("POWERLIST")){
                JSONObject adminPower = JSONObject.parseObject(userInfo.get(i).get(1));
                adminHomePage = adminPower.getJSONArray("homePage");
                userInfo.remove(i);
            }
        }
        JSONObject userPower = JSONObject.parseObject(userInfo.get(0).get(1));
        userHomePage = userPower.getJSONArray("homePage");

        //将admin的权限与用户权限做对比
        for (int i = 0; i < adminHomePage.size(); i++){
            JSONArray oneLine = adminHomePage.getJSONArray(i);
            for (int ii = 0; ii < oneLine.size(); ii++){
                String current = adminHomePage.getJSONArray(i).getString(ii);
                if (!userHomePage.contains(current)){
                    oneLine.set(ii, "x;"+current);
                    adminHomePage.set(i, oneLine);
                }
            }
        }

        return adminHomePage.toJSONString();
    }

}
